package com.weiyi.weiman.service.comics.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weiyi.weiman.domain.Const.ComicsConst;
import com.weiyi.weiman.domain.status.EntityStatus;
import com.weiyi.weiman.domain.status.ResultStatus;
import com.weiyi.weiman.exception.APIException;
import com.weiyi.weiman.mapper.comics.ComicsChapterMapper;
import com.weiyi.weiman.mapper.comics.ComicsMapper;
import com.weiyi.weiman.service.comics.ComicsService;
import com.weiyi.weiman.utils.RedisUtils;
import comics.Comics;
import comics.ComicsChapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhang
 * @Date 2021/5/11 上午11:52
 * @Description 漫画的公共业务类
 * @Version 1.0
 **/
@Slf4j
@Service
public class ComicsServiceImpl implements ComicsService {

    @Autowired
    private ComicsMapper comicsMapper;
    @Autowired
    private ComicsChapterMapper chapterMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Comics getComics(long comicsId) {
        String comicsKey = ComicsConst.COMICS_REDIS_PRE + comicsId;
        Comics comics = null;
        log.info("查找漫画:{}", comicsId);
        if (!redisUtils.hasKey(comicsKey)) {
            log.info("漫画:"+comicsId+"不在缓存中");
            QueryWrapper<Comics> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("comics_id", comicsId+"")
                    .eq("comics_status", EntityStatus.STATUS_NORMAL.getCode());
            comics = comicsMapper.selectOne(queryWrapper);
            if (Objects.isNull(comics)) {
                log.error(comicsId+"漫画不存在");
                throw new APIException("漫画不存在");
            }
            HashMap<String,String> comicsMap = JSON.parseObject(JSON.toJSONString(comics)
                    , new TypeReference<HashMap<String,String>>(){});
            redisUtils.hPutAll(comicsKey, comicsMap);
            log.info("漫画:"+comicsId+"已加入缓存中");
        } else {
            //获取redis中comics的数据，并转为comics对象
            Map<Object, Object> comicsMap = redisUtils.hGetAll(comicsKey);
            comics = JSON.parseObject(JSON.toJSONString(comicsMap), Comics.class);
            log.info("漫画{}在缓存中,已获取数据", comicsId);
        }
        redisUtils.setExpire(comicsKey, 200, TimeUnit.HOURS);
        return comics;
    }

    @Override
    public ComicsChapter getChapter(long chapterId) {
        String chapterContentKey = ComicsConst.CHAPTER_CONTENT_REDIS_PRE + chapterId;
        ComicsChapter comicsChapter = null;
        if (!redisUtils.hasKey(chapterContentKey)) {
            comicsChapter = chapterMapper.selectById(chapterId);
            if (Objects.isNull(comicsChapter))
                throw new APIException(ResultStatus.NON_CHAPTER_ERROR);
            redisUtils.set(chapterContentKey, JSON.toJSONString(comicsChapter));
        } else {
            comicsChapter = JSON.parseObject(redisUtils.get(chapterContentKey), ComicsChapter.class);
        }
        //刷新过期时间
        redisUtils.setExpire(chapterContentKey, 24, TimeUnit.HOURS);
        return comicsChapter;
    }

    /**
     * 判断redis中是否有chapter列表信息,如果没有则进行设置
     * @param comicsId
     */
    @Override
    public boolean setChapterListRedis(long comicsId) {
        String chapterKey = ComicsConst.CHAPTER_LIST_REDIS_PRE + comicsId;
        if (redisUtils.lLen(chapterKey) == 0) {
            QueryWrapper<ComicsChapter> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("comics_id",comicsId)
                    .orderByAsc("chapter_num");
            List<ComicsChapter> chapters = chapterMapper.selectList(queryWrapper);
            if (Objects.isNull(chapters)) {
                log.error("漫画:{}未找到章节信息", comicsId);
                throw new APIException(ResultStatus.NON_CHAPTER_ERROR);
            }
            for (ComicsChapter chapter : chapters) {
                redisUtils.lRightPush(chapterKey, JSON.toJSONString(chapter));
            }
            log.info("漫画:{}章节列表信息已存入缓存中", comicsId);
        }
        redisUtils.setExpire(chapterKey, 24, TimeUnit.HOURS);
        return true;
    }

    @Override
    public List<Comics> getLatestComicsIndex(int limit) {
        return comicsMapper.getLatestComicsIndex(limit);
    }

}
